/*
Kakine
ActionScript Framework
Copyright © 2011, PUNY, LLC.

This file is part of KAKINE.

KAKINE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

KAKINE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with KAKINE.  If not, see <http://www.gnu.org/licenses/>.
*/ 
package com.puny.utils
{
	public class WeightedRandom extends Object implements IWeightedIndex
	{
		private const _indexes:Array = new Array();
		private var _total:uint;
		private var _pos:uint;
		private var _last:WeightedIndex;
		public function WeightedRandom(weights:Array)
		{
			var from:uint = 0;
			var length:uint = weights.length;
			var weight:uint;
			for(var i:uint = 0;i < length;i++) {
				weight = weights[i];
				if (weight > 0) {
					_indexes.push(new WeightedIndex(i, from, weight));
					from += weight;
				}
			}
			_total = from;
			findIndex();
		}
		
		public function random():uint {
			var ret:uint = _last.index;
			findIndex();
			return ret;
		}
		
		private function search(element:WeightedIndex, index:int, arr:Array):Boolean {
			_last = element;
			return !element.hit(_pos);
		}
		
		private function findIndex():void {
			_pos = Random.integer(_total);
			_indexes.every(search);
		}
	}
}